/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Matrix.java
 *
 * Created on 06.06.2011, 14:48:32
 */
package sixsigma;

import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.RowSorter;
import javax.swing.SortOrder;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author SS
 */
public class MatrixGUI extends javax.swing.JFrame implements MouseListener{

    String txt = "";
    
    DbKomm dbk = new DbKomm();

    /** Creates new form Matrix */
    public MatrixGUI() {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(MatrixGUI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(MatrixGUI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(MatrixGUI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(MatrixGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        initComponents();
        jTable1.addMouseListener(this);
        addMouseListener(this);
        super.setLocationRelativeTo(null);
        matrics();
    }

    public void matrics(){
        
        String PID = Integer.toString(MainGUI.projectId);
        String [][] FP = getData("SELECT DISTINCT fr.FR_TXT, f.FR_ID, fr.FR_GROUP_ID FROM fr_dp_rel f INNER JOIN FR fr ON f.FR_ID = fr.FR_ID AND fr.FR_PROJECT_ID ="+PID+";");
        String [][] FPG = getData("SELECT FR_GROUP_ID,FR_GROUP_TEXT FROM fr_group");
        String [][] DP = getData("SELECT DISTINCT dp.DP_TXT, f.DP_ID, dp.DP_GROUP_ID FROM fr_dp_rel f INNER JOIN DP dp ON f.DP_ID = dp.DP_ID AND dp.DP_PROJECT_ID ="+PID+";");
        String [][] DPG = getData("SELECT DP_GROUP_ID,DP_GROUP_TXT FROM dp_group");
        String [][] crit = getData("SELECT FR_ID, DP_ID, CRIT_ID FROM fr_dp_rel");
        String [] columnNames = new String[DP.length];
        String [] columnNames2 = new String[DP.length+2]; 
        String jRID, jCID, FPGName="", DPGName="";


        //Hier werden die Columns erstellt
        for (int i=0; i<DP.length; i++){
            for (int j=0; j<DPG.length; j++){
                if (Integer.parseInt(DPG[j][0])==Integer.parseInt(DP[i][2])) DPGName = DPG[j][1];
            }        
            columnNames[i] = DPGName+"_"+DP[i][0]+" ("+DP[i][1]+")";
        }
        Arrays.sort(columnNames);
        columnNames2[0] = "(0)"; 
        columnNames2[1] = "IDs (0)";
        for (int i=2; i<columnNames2.length; i++){
            columnNames2[i] = columnNames[i-2];
        }
        
        //Hier werden die Zeilen erstellt
        String[][] data = new String[FP.length][columnNames2.length];
        for (int i=0; i<FP.length; i++){
            //IDs der Zeilen in Spalte: 1
            for (int j=0; j<FPG.length; j++){
                if (Integer.parseInt(FPG[j][0])==Integer.parseInt(FP[i][2])) FPGName = FPG[j][1];
            }     
            data[i] = new String[columnNames2.length];
            data[i][0] = FPGName+"_"+FP[i][0];
            data[i][1] = FP[i][1];
        }
        
        //Table Model überschreiben
        DefaultTableModel model = new DefaultTableModel(data, columnNames2){
                @Override
                public boolean isCellEditable(int row, int column) {
                   //Alle Zellen nicht editierbar
                   return false;
                }
        };
        jTable1.setModel(model);
        
        //VerticalTableHeaderCellRenderer für alle Table Header setzen!
        VerticalTableHeaderCellRenderer headerRenderer = new VerticalTableHeaderCellRenderer();
        Enumeration<TableColumn> columns = jTable1.getColumnModel().getColumns();
        while (columns.hasMoreElements()) {
            TableColumn c = columns.nextElement();
            c.setHeaderRenderer(headerRenderer);
            //Mindestbreite
            c.setPreferredWidth(30);
            c.setIdentifier(this);
        }
        
        //Breite der ersten Spalte ändern
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(200);
        jTable1.getColumnModel().getColumn(1).setResizable(false);
        //IDs verstecken
        jTable1.getColumnModel().getColumn(1).setMaxWidth(0);
        jTable1.getColumnModel().getColumn(1).setMinWidth(0);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(0);
        
        //Spalten IDs hinzufügen
        for (int i=0; i<jTable1.getColumnModel().getColumnCount(); i++){
            jTable1.getColumnModel().getColumn(i).setIdentifier(getID(jTable1.getColumnModel().getColumn(i).getHeaderValue().toString()));
        }
        
        //Zeilen in Tabelle durchgehen
        for (int j=0; j<jTable1.getRowCount(); j++){
            //Spalten in Tabellenzeile durchgehen und Kritikalität aus der Datenbank hineinschreiben
            for (int i=2; i<jTable1.getColumnCount(); i++){
                jRID = jTable1.getValueAt(j,1).toString();
                jCID = jTable1.getColumnModel().getColumn(i).getIdentifier().toString();
                jTable1.setValueAt("X", j, i);
                //Kritikalität aus der DB auslesen und schreiben
                for(int k=0; k<crit.length; k++) {
                    if(crit[k][0].equals(jRID) && crit[k][1].equals(jCID) && crit[k][2]!= null) {
                        switch(Integer.parseInt(crit[k][2])) {
                          case 1: jTable1.setValueAt("+",j,i); break;
                          case 2: jTable1.setValueAt("0",j,i); break;
                          case 3: jTable1.setValueAt("-",j,i); break;
                        }
                    } 
                }
            }
        }
        
        //Zeilen sortieren
        TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(jTable1.getModel());
        List <RowSorter.SortKey> sortKeys = new ArrayList<RowSorter.SortKey>();
        sortKeys.add(new RowSorter.SortKey(0, SortOrder.ASCENDING));
        sorter.setSortKeys(sortKeys); 
        jTable1.setRowSorter(sorter);
    }
    
    private String getID(String Item){
        String ID="";
        if (Item!=null) ID = Item.substring(Item.lastIndexOf("(")+1, Item.lastIndexOf(")"));
        return ID;
    }
    
    public void mouseClicked(MouseEvent e) {
        Point p = e.getPoint();
        int y = jTable1.rowAtPoint(p);
        int x = jTable1.columnAtPoint(p);
        changeProperty(x, y);
        farbeAendern(x, y);
    }

    public void mousePressed(MouseEvent e) {
        // Wenn notwenig noch implementieren
    }

    public void mouseReleased(MouseEvent e) {
        // Wenn notwenig noch implementieren
    }

    public void mouseEntered(MouseEvent e) {
        // Wenn notwenig noch implementieren
    }

    public void mouseExited(MouseEvent e) {
        // Wenn notwenig noch implementieren
    }

    private void changeProperty(int x, int y) {
        txt = String.valueOf(jTable1.getValueAt(y, x));

        if(x==0)
        {

        }
        else{
            if(txt == null || txt.equals("") || txt.equals("null")){
            jTable1.setValueAt("0", y, x);
            txt = "0";
            }
            else if(txt.equals("0")){
            jTable1.setValueAt("+", y, x);
             }
            else if(txt.equals("+")){
            jTable1.setValueAt("-", y, x);
            }
            else if(txt.equals("-")){
            jTable1.setValueAt("", y, x);
            }
            else{
                ;
            }
        }

    }

    private void farbeAendern(int x, int y) {
        //Noch implementieren
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        Status = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null}
            },
            new String [] {
                "Title 1"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jTable1.setAutoscrolls(false);
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setText("Relationstabelle (angezeigt werden alle definierten Abhängigkeiten)");

        jButton1.setText("speichern");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel2.setText("Legende: - kritisch, 0 normal, + nicht kritisch");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(Status)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 160, Short.MAX_VALUE)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 286, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(Status)
                            .addComponent(jButton1)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(323, 323, 323)
                        .addComponent(jLabel2)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        for (int j=0; j<jTable1.getRowCount(); j++){
            for (int i=2; i<jTable1.getColumnCount(); i++){
                
                if(jTable1.getValueAt(j, i)!=null){
                    
                    String jCID = jTable1.getColumnModel().getColumn(i).getIdentifier().toString();
                    String jRID = jTable1.getValueAt(j,1).toString();
                   
                    String zInhalt =jTable1.getValueAt(j, i).toString();

                    if(zInhalt.equals("+")){
                       setData("UPDATE fr_dp_rel SET CRIT_ID = 1 WHERE FR_ID = "+jRID+" AND DP_ID = "+jCID+";");
                    }else if(zInhalt.equals("0")){
                        setData("UPDATE fr_dp_rel SET CRIT_ID = 2 WHERE FR_ID = "+jRID+" AND DP_ID = "+jCID+";");
                    }else if(zInhalt.equals("-")){
                        setData("UPDATE fr_dp_rel SET CRIT_ID = 3 WHERE FR_ID = "+jRID+" AND DP_ID = "+jCID+";");
                    }else if(zInhalt.equals("X")){
                        ;
                    }else if(zInhalt.equals("")){
                        setData("DELETE FROM fr_dp_rel WHERE FR_ID = "+jRID+" AND DP_ID = "+jCID+";");
                    }

                }
            }
        }
        Status.setText("Erfolgreich gespeichert!");
    }//GEN-LAST:event_jButton1ActionPerformed
   
    
    private String[][] getData(String SQL){

        try {dbk.open();}catch(Exception ex){
            Logger.getLogger(MatrixGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        String[][] ergebnis = dbk.einfachArrayAuslesen(SQL);
        try {dbk.close();}catch(Exception ex){
            Logger.getLogger(MatrixGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        return ergebnis;
    }

    private void setData(String SQL){
        try {dbk.open();}catch(Exception ex){
            Logger.getLogger(MatrixGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        dbk.execute(SQL);
        try {dbk.close();}catch(Exception ex){
            Logger.getLogger(MatrixGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel Status;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables

}
